package com.samapp.indent;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.dragon.httpclient_util.HttpClientThread;
import com.dragon.httpclient_util.HttpResultHandle;
import com.dragon.httpclient_util.JsonUtils;
import com.dragon.image.ImageFormatConversion;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.samapp.MyApplication;
import com.samapp.R;
import com.samapp.db.SamappDB;
import com.samapp.entity.Client;
import com.samapp.entity.Indent;
import com.samapp.utils.json.GsonUtil;

/**
 * 添加订单
 */
public class AddIndentActivity extends Activity implements OnClickListener {

	/** 返回按钮 */
	private Button btnBack = null;
	/** 创建订单按钮 */
	private Button btnCreateIndent = null;
	/** 下一步按钮 */
	private Button btnNext = null;
	/** 客户 */
	private Spinner spinnerClientName = null;
	/** 订单号 */
	private EditText orderID = null;
	/** 业务类型 */
	private EditText etBusType = null;
	/** 取证方式 */
	private EditText etFetchType = null;
	/** 证书类型 */
	private EditText etLceType = null;
	/** 报告语言 */
	private EditText etLanguage = null;
	/** 备注 */
	private EditText etRemark = null;
	/** 是否加急 */
	private RadioButton rBtnIsUrgent_true = null;
	/** 是否分包 */
	private RadioButton rBtnIsPacket_true = null;
	/** 是否退样 */
	private RadioButton rBtnIsReturn_true = null;
	/** 是否短信通知 */
	private RadioButton rBtnIsSms_true = null;
	private MyApplication myApplication = MyApplication.getApplicationInstance();
	/** 客户数组 */
	private List<Client> mClients = new ArrayList<Client>();
	/** 客户名数组 */
	private List<String> mClientNames = new ArrayList<String>();
	/** 被选中的客户 */
	private Client mClient = null;

	/** 签名 */
	private ImageView imageAutograph = null;
	/** 上传签名 */
	private Button btnUploadingAutograph = null;
	/** 订单明细 */
	private Button btnIndentDetail = null;
	private IndentDetailAdapter mIndentDetailAdapter;
	/** 添加样品详情 */
	private Button btnSampleDetails = null;
	/** 订单数组 */
	private List<Indent> mIndents = new ArrayList<Indent>();
	/** 签名请求码 */
	public static final int CODE_AUTOGRAPH = 0xa0;
	/** 添加样品详情请求码 */
	public static final int CODE_ADD_SAMPLE_DETAILS = 0xa1;

	private final String[] text = { " " };

	/** 上传签名 */
	public static final int MSG_UP_AUTOGRAPH = 0X193;
	/** 创建订单 */
	public static final int MSG_CREATE_INDENT = 0X194;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == MSG_UP_AUTOGRAPH) {
				btnUploadingAutograph.setText(text[0]);
			} else if (msg.what == MSG_CREATE_INDENT) {
				Toast.makeText(AddIndentActivity.this, text[0], Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_indent);
		init();
	}

	// @Override
	// protected void onRestart() {
	// super.onRestart();
	// mIndentDetailAdapter.notifyDataSetChanged();
	// LinearLayout.LayoutParams linearParams1 = (LinearLayout.LayoutParams)
	// listViewIndentDetail.getLayoutParams();
	// linearParams1.height = 148 *
	// myApplication.newIndent.getOrderDetail().size();
	// listViewIndentDetail.setLayoutParams(linearParams1);
	//
	// mSampleDetailAdapter.notifyDataSetChanged();
	// LinearLayout.LayoutParams linearParams2 = (LinearLayout.LayoutParams)
	// listViewSampleDetails.getLayoutParams();
	// linearParams2.height = 148 * myApplication.newIndent.getSamples().size();
	// listViewSampleDetails.setLayoutParams(linearParams2);
	// }

	private void init() {
		initView();
		initData();
		initListener();
	}

	private void initView() {
		btnBack = (Button) findViewById(R.id.btn_back);
		btnCreateIndent = (Button) findViewById(R.id.btn_create_indent);
		orderID = (EditText) findViewById(R.id.orderID);
		spinnerClientName = (Spinner) findViewById(R.id.spinner_client_name);
		etBusType = (EditText) findViewById(R.id.busType);
		etFetchType = (EditText) findViewById(R.id.fetchType);
		etLceType = (EditText) findViewById(R.id.lceType);
		etLanguage = (EditText) findViewById(R.id.language);
		etRemark = (EditText) findViewById(R.id.remark);
		rBtnIsUrgent_true = (RadioButton) findViewById(R.id.isUrgent_true);
		rBtnIsPacket_true = (RadioButton) findViewById(R.id.isPacket_true);
		rBtnIsReturn_true = (RadioButton) findViewById(R.id.isReturn_true);
		rBtnIsSms_true = (RadioButton) findViewById(R.id.isSms_true);
		btnNext = (Button) findViewById(R.id.btn_next);
		// imageAutograph = (ImageView) findViewById(R.id.autograph);
		// btnUploadingAutograph = (Button)
		// findViewById(R.id.btn_uploading_autograph);
		// btnIndentDetail = (Button) findViewById(R.id.indent_detail);
		// btnSampleDetails = (Button) findViewById(R.id.sample_details);
		// listViewIndentDetail = (ListView)
		// findViewById(R.id.listview_indent_detail);

	}

	private void initData() {
		myApplication.newIndent = new Indent();
		orderID.setText(Math.abs(UUID.randomUUID().getMostSignificantBits()) + "");
		SamappDB samappDB = new SamappDB(AddIndentActivity.this, MyApplication.getApplicationInstance().databaseVesion);
		Cursor cursor = samappDB.select();
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			Client client = new Client(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6),
					cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13), cursor.getString(14),
					cursor.getString(15));
			mClients.add(client);
			mClientNames.add(client.getCname());
		}
		initClientNameSpinner();
	}

	private void initClientNameSpinner() {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mClientNames);
		adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spinnerClientName.setAdapter(adapter);
		spinnerClientName.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				mClient = mClients.get(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				mClient = mClients.get(0);
			}
		});
	}

	private void initListener() {
		btnBack.setOnClickListener(this);
		btnNext.setOnClickListener(this);
		btnCreateIndent.setOnClickListener(this);
		// imageAutograph.setOnClickListener(this);
		// btnUploadingAutograph.setOnClickListener(this);
		// btnIndentDetail.setOnClickListener(this);
		// btnSampleDetails.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.btn_next:
			setData();
			skip(SampleDetailsActivity.class);
			break;
		case R.id.btn_create_indent:
			setData();
			createIndent();
			finish();
			break;
		// case R.id.autograph:
		// Intent intentAutograph = new Intent(this, PaintActivity.class);
		// startActivityForResult(intentAutograph, CODE_AUTOGRAPH);
		// break;
		// case R.id.btn_uploading_autograph:
		// uploadingAutograph();
		// break;
		// case R.id.indent_detail:
		// // Intent intentIndentDetail = new Intent(this,
		// // IndentDetailActivity.class);
		// // startActivityForResult(intentIndentDetail,
		// // CODE_ADD_SAMPLE_DETAILS);
		// skip(IndentDetailActivity.class);
		// break;
		// case R.id.sample_details:
		// skip(SampleDetailsActivity.class);
		// break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		switch (resultCode) {
		case PaintActivity.CODE_AUTOGRAPH:
			imageAutograph.setBackgroundDrawable(new BitmapDrawable(myApplication.bitmapAutograph));
			try {
				ImageFormatConversion.bitmapToFile(((BitmapDrawable) imageAutograph.getBackground()).getBitmap(), "autograph.JPEG", "/mnt/sdcard/samapp/");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	/** 跳转页面 */
	private void skip(Class<?> cls) {
		Intent intent = new Intent(this, cls);
		startActivity(intent);
	}

	/**
	 * 上传签名
	 */
	private void uploadingAutograph() {
		String url = myApplication.url + "uploadImg.htm";
		RequestParams params = new RequestParams();
		params.addBodyParameter("accessToken", "5C9.yx0S");
		params.addBodyParameter("type", "1");
		params.addBodyParameter("file", new File("/mnt/sdcard/temp_head_image.jpg"));
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				Log.i("Long", arg0.result);
				text[0] = JsonUtils.getValue(arg0.result, "msg");
				mHandler.sendEmptyMessage(MSG_UP_AUTOGRAPH);
				myApplication.newIndent.setSignPath(JsonUtils.getValue(arg0.toString(), "path"));
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				Log.i("Long", arg1);
				text[0] = JsonUtils.getValue(arg1, "msg");
				mHandler.sendEmptyMessage(MSG_UP_AUTOGRAPH);
			}
		});
	}

	private void setData() {
		myApplication.newIndent.setCnumber(mClient.getNumber());
		myApplication.newIndent.setNumber(orderID.getText().toString());
		myApplication.newIndent.setBusType(etBusType.getText().toString().trim());
		myApplication.newIndent.setFetchType(etFetchType.getText().toString().trim());
		myApplication.newIndent.setLceType(etLceType.getText().toString().trim());
		myApplication.newIndent.setUnumber(myApplication.currentUser.getUserName());
		myApplication.newIndent.setLanguage(etLanguage.getText().toString().trim());
		myApplication.newIndent.setRemark(etRemark.getText().toString().trim());
		if (rBtnIsUrgent_true.isChecked()) {
			myApplication.newIndent.setIsUrgent("true");
		} else {
			myApplication.newIndent.setIsUrgent("false");
		}
		if (rBtnIsPacket_true.isChecked()) {
			myApplication.newIndent.setIsPacket("true");
		} else {
			myApplication.newIndent.setIsPacket("false");
		}
		if (rBtnIsReturn_true.isChecked()) {
			myApplication.newIndent.setIsReturn("true");
		} else {
			myApplication.newIndent.setIsReturn("false");
		}
		if (rBtnIsSms_true.isChecked()) {
			myApplication.newIndent.setIsSms("true");
		} else {
			myApplication.newIndent.setIsSms("false");
		}
	}

	private void createIndent() {
		String url = myApplication.url + "createOrder.htm";
		Map<String, String> myMap = new HashMap<String, String>();
		myMap.put("accessToken", "5C9.yx0S");
		myMap.put("cnumber", myApplication.newIndent.getCnumber());
		myMap.put("number", myApplication.newIndent.getNumber());
		myMap.put("busType", myApplication.newIndent.getBusType());
		myMap.put("fetchType", myApplication.newIndent.getFetchType());
		myMap.put("lceType", myApplication.newIndent.getLceType());
		myMap.put("unumber", myApplication.newIndent.getUnumber());
		myMap.put("Language", myApplication.newIndent.getLanguage());
		myMap.put("isUrgent", myApplication.newIndent.getIsUrgent());
		myMap.put("isPacket", myApplication.newIndent.getIsPacket());
		myMap.put("isReturn", myApplication.newIndent.getIsReturn());
		myMap.put("isSms", myApplication.newIndent.getIsSms());
		myMap.put("remark", myApplication.newIndent.getRemark());
		myMap.put("signPath", myApplication.newIndent.getSignPath());
		myMap.put("orderDetail", GsonUtil.getGson().toJson(myApplication.newIndent.getOrderDetail()));
		myMap.put("samples", GsonUtil.getGson().toJson(myApplication.newIndent.getSamples()));
		HttpClientThread.getmHttpClientThread().post(url, myMap, new HttpResultHandle() {

			@Override
			public void onSuccess(String response) {
				String code = JsonUtils.getValue(response, "code");
				if ("0".equals(code)) {
					// text[0] = JsonUtils.getValue(response, "discount");
					text[0] = JsonUtils.getValue(response, "msg");
					mHandler.sendEmptyMessage(MSG_CREATE_INDENT);
					finish();
				} else {
					text[0] = JsonUtils.getValue(response, "msg");
					mHandler.sendEmptyMessage(MSG_CREATE_INDENT);
				}
			}

			@Override
			public void onFailure(int statusCode) {
				text[0] = "连接服务器失败，状态码：" + statusCode;
				mHandler.sendEmptyMessage(MSG_CREATE_INDENT);
			}
		});
	}

}
